<template>
  <div class="player" v-show="playlist.length>0">
    <transition name="normal"
                @enter="enter"
                @after-enter="afterEnter"
                @leave="leave"
                @after-leave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <!--      背景图-->
        <div class="background">
          <img width="100%" height="100%" alt="图片走丢了" :src="this.currentSong.image">
        </div>
        <!--      顶部-->
        <div class="top">
          <!--        返回按钮-->
          <div class="back" @click="back">
            <i class="icon-back"></i>
          </div>
          <!--        歌曲名-->
          <h1 class="title" v-html="this.currentSong.name"></h1>
          <!--        歌手名-->
          <h2 class="subtitle" v-html="this.currentSong.singer"></h2>
        </div>
        <!--      中间部分-->
        <!--      唱片-->
        <div class="middle"
             @touchstart.prevent="middleTouchStart"
             @touchmove.prevent="middleTouchMove"
             @touchend="middleTouchEnd"
        >
          <!--        唱片左部-->
          <div class="middle-l" ref="middleL">
            <div class="cd-wrapper" ref="cdWrapper">
              <div class="cd" :class="cdCls">
                <!--              唱片图片-->
                <img class="image" :src="this.currentSong.image">
              </div>
            </div>
            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{playingLyric}}</div>
            </div>
          </div>
          <!--          唱片右部，歌词部分-->
          <scroll class="middle-r" ref="lyricList" :data="currentLyric&&currentLyric.lines">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p ref="lyricLine"
                   class="text" v-for="(line,index) in currentLyric.lines"
                   :class="{'current':currentlineNum === index}"
                   :key="index">{{line.txt}}</p>
              </div>
            </div>
          </scroll>
        </div>
        <!--      底部操作区域-->
        <div class="bottom">
          <!--          表示分页的点点-->
          <div class="dot-wrapper">
            <span class="dot" :class="{'active':currentShow==='cd'}"></span>
            <span class="dot" :class="{'active':currentShow==='lyric'}"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{fomateTime(currentTime)}}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="_percentChange"></progress-bar>
            </div>
            <span class="time time-r">{{fomateTime(currentSong.duration)}}</span>
          </div>
          <div class="operators">
            <div class="icon i-left">
              <i :class="iconMode" @click="changeMode"></i>
            </div>
            <!--          上一曲-->
            <div class="icon i-left">
              <i class="icon-prev" @click="pre()"></i>
            </div>
            <!--          播放按钮-->
            <div class="icon i-center">
              <i :class="playIcon" @click="togglePlaying"></i>
            </div>
            <!--          下一曲-->
            <div class="icon i-right">
              <i class="icon-next" @click="next()"></i>
            </div>
            <!--          收藏-->
            <div class="icon i-right">
              <i class="icon icon-not-favorite"></i>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <!--    底部播放组件-->
    <transition name="mini">
      <div class="mini-player" v-show="!fullScreen" @click="open()">
        <!--      底部操作栏唱片图标-->
        <div class="icon">
          <img :class="cdCls" width="40" height="40" :src="this.currentSong.image">
        </div>
        <!--      歌名及歌手名-->
        <div class="text">
          <h2 class="name" v-html="this.currentSong.name"></h2>
          <p class="desc" v-html="this.currentSong.singer"></p>
        </div>
        <!--        迷你播放器播放按钮-->
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i :class="playMiniIcon" class="icon-mini" @click.stop="togglePlaying"></i>
          </progress-circle>
        </div>
        <div class="control">
          <i class="icon-playlist" @click.stop="showPlay"></i>
        </div>
      </div>
    </transition>
    <!--    播放清单-->
    <div class="playlist-wrapper">
      <play-list ref="playList"></play-list>
    </div>
    <audio ref="audio" :src="this.currentSong.url" @timeupdate="timeUpdate" @ended="end"></audio>
  </div>
</template>

<script type="text/ecmascript-6">
  import {mapGetters, mapMutations} from 'vuex'
  import animations from 'create-keyframe-animation'
  import {prefixStyle} from 'common/js/dom'
  import {playMode} from 'common/js/config'
  import {shuflle} from 'common/js/util'
  import Lyric from 'lyric-parser'
  import ProgressBar from 'base/progress-bar/progress-bar'
  import ProgressCircle from 'base/progress-circle/progress-circle'
  import Scroll from 'base/scroll/scroll'
  import PlayList from 'components/play-list/play-list'

  const transform = prefixStyle('transform')
  const transitionDuration = prefixStyle('transitionDuration')

  export default {
    data () {
      return {
        // 当前歌曲播放时间
        currentTime: 0,
        // mini播放器的圆半径
        radius: 32,
        // 当前歌词
        currentLyric: null,
        // 当前歌词播放到第几行
        currentlineNum: 0,
        // 表示播放页在cd页或者歌词页
        currentShow: 'cd',
        // 当前正在播放的歌词
        playingLyric: ''
      }
    },
    created () {
      this.touch = {}
    },
    methods: {
      // 展示播放列表
      showPlay () {
        this.$refs.playList.showPlayList = true
      },
      // 切换唱片页与歌词页
      middleTouchStart (e) {
        // 判断touch变量是否初始化
        this.touch.initiated = true
        // 判断是否是滑动
        this.touch.move = false
        // 纪录初始的x,y
        const touch = e.touches[0]
        this.touch.startX = touch.pageX
        // this.touch.startY = touch.pageY
      },
      // 手指滑动过程中的事件处理
      middleTouchMove (e) {
        if (!this.touch.initiated) {
          return
        }
        const touch = e.touches[0]
        // 手指滑动的距离
        const deltaX = touch.pageX - this.touch.startX
        // const deltaY = touch.pageY - this.touch.startY
        // if (Math.abs(deltaY) > Math.abs(deltaX)) {
        //   return
        // }
        // 初始的距离
        const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
        // 滑动的距离
        const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
        // 如果没滑动是不能切换歌词页的
        if (!this.touch.moved) {
          this.touch.moved = true
        }
        // 滑动的动画时间
        const TIME = 0
        // if (!this.touch.moved) {
        //   this.touch.moved = true
        // }
        // 滑动百分比
        this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.lyricList.$el.style[transitionDuration] = `${TIME}ms`
        // 根据滑动的距离改变cd页的透明度
        this.$refs.middleL.style.opacity = 1 - this.touch.percent
        this.$refs.middleL.style[transitionDuration] = 0
      },
      // 手指滑动结束时的事件处理
      middleTouchEnd () {
        if (!this.touch.moved) {
          return
        }
        // 当手指滑动结束时，如果左往右滑，大于10%，就让歌词界面整个过去
        let offsetWidth
        let opacity
        if (this.currentShow === 'cd') {
          if (this.touch.percent > 0.1) {
            offsetWidth = -window.innerWidth
            opacity = 0
            // 改变控制点点的变量
            this.currentShow = 'lyric'
          } else {
            offsetWidth = 0
            opacity = 1
          }
        } else {
          // 当从右往左滑
          if (this.touch.percent < 0.9) {
            offsetWidth = 0
            opacity = 1
            this.currentShow = 'cd'
          } else {
            offsetWidth = -window.innerWidth
            opacity = 0
          }
        }
        // 歌词页切换的动画时间
        const TIME = 300
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px,0,0)`
        this.$refs.lyricList.$el.style[transitionDuration] = `${TIME}ms`
        this.$refs.middleL.style.opacity = opacity
        this.$refs.middleL.style[transitionDuration] = `${TIME}ms`
        this.touch.initiated = false
      },
      // 歌曲播放完毕
      end () {
        // 单曲循环
        if (this.mode === playMode.loop) {
          this.$refs.audio.currentTime = 0
          this.$refs.audio.play()
          // 让歌词回到开始的位置
          if (this.currentLyric) {
            this.currentLyric.seek(0)
            this.$refs.lyricList.scrollToElement(0, 0, 1000)
          }
        } else {
          // 随机播放及顺序播放
          this.next()
        }
      },
      // 改变播放模式
      changeMode () {
        // 只有三种播放模式，所以对3取余
        const mode = (this.mode + 1) % 3
        // 使用vuex的mutations改变共享模式数据
        this.setMode(mode)
        let list = null
        // 随机播放时，生成一个随机歌单
        if (this.mode === playMode.random) {
          list = shuflle(this.sequenceList[0].slice(0, 79))
        } else {
          list = this.sequenceList[0]
        }
        this._resetCurrentIndex(list)
        this.setPlayList(list)
      },
      // 随机模式时要保证当前歌曲index不变
      _resetCurrentIndex (list) {
        let index = list.findIndex((item) => {
          return item.id === this.currentSong.id
        })
        this.setCurrentIndex(index)
      },
      // 滑动播放进度条的时候改变播放时间
      _percentChange (percent) {
        this.currentTime = this.currentSong.duration * percent
        this.$refs.audio.currentTime = this.currentTime
        // 播放
        if (!this.playing) {
          this.togglePlaying()
        }
        // 点击进度条，改变歌词的播放进度
        if (this.currentLyric) {
          this.currentLyric.seek(this.currentTime * 1000)
        }
      },
      // 歌曲播放时间
      timeUpdate (e) {
        this.currentTime = e.target.currentTime
      },
      // 规格化播放时间
      fomateTime (interval) {
        const time = interval | 0
        const minute = time / 60 | 0
        const second = this._pad(time % 60)
        return `${minute}:${second}`
      },
      // 给秒位数补0
      _pad (num, n = 2) {
        let len = num.toString().length
        while (len < n) {
          num = '0' + num
          len++
        }
        return num
      },
      // 播放按钮来回切换播放状态
      togglePlaying () {
        this.setPlaying(!this.playing)
        // 来回切换歌词的播放状态
        if (this.currentLyric) {
          this.currentLyric.togglePlay()
        }
      },
      // 返回键
      back () {
        this.setFullScreen(false)
      },
      // 打开播放页
      open () {
        this.setFullScreen(true)
      },
      // cdWrapper初始位置设置及进入动画
      enter (el, done) {
        const {x, y, scale} = this._getPosAndScale()
        // cdWrapper动画过渡方式
        let animation = {
          0: {
            transform: `translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          60: {
            transform: `translate3d(0,0,0) scale(1.1)`
          },
          100: {
            transform: `translate3d(0,0,0) scale(1)`
          }
        }
        // 注册cdWrapper的过渡动画
        animations.registerAnimation({
          name: 'move',
          animation,
          presets: {
            duration: 1011,
            easing: 'linear'
          }
        })
        // 跑动画
        animations.runAnimation(this.$refs.cdWrapper, 'move', done)
      },
      // 动画结束，去除animations效果
      afterEnter () {
        setTimeout(() => {
          animations.unregisterAnimation('move')
          this.$refs.cdWrapper.style.animation = ''
        }, 800)
      },
      // cdWrapper转化为mini-wrapper的icon动画
      leave (el, done) {
        this.$refs.cdWrapper.style.transition = `all 1s`
        const {x, y, scale} = this._getPosAndScale()
        this.$refs.cdWrapper.style[transform] = `translate3d(${x}px,${y}px,0) scale(${scale})`
        this.$refs.cdWrapper.addEventListener('transitionend', done)
      },
      // 动画结束
      afterLeave () {
        this.$refs.cdWrapper.style.trasition = ''
        this.$refs.cdWrapper.style[transform] = ''
      },
      // 上一曲
      pre () {
        // 当是第一首的时候，到最后一首
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist[0].length - 1
        }
        // 不然歌曲的currentIndex到下一首
        this.setCurrentIndex(index)
        this.songReady = false
      },
      // 下一曲
      next () {
        let index = this.currentIndex + 1
        console.log(this.currentIndex)
        // 当是第一首的时候，到最后一首
        if (index === this.playlist[0].length - 1) {
          index = 0
        }
        // 不然歌曲的currentIndex到下一首
        this.setCurrentIndex(index)
        this.songReady = false
      },
      // 拿到当前歌曲的歌词
      // getLyric () {
      //   this.currrentSong.getSongLyric().then((lyric) => {
      //     this.currentLyric = new Lyric(lyric)
      //     if (this.playing) {
      //       this.currentLyric.play()
      //     }
      //     console.log(lyric)
      //   })
      // },
      // 歌词播放的回调函数，用于确定播放时的样式
      handleLyric ({lineNum, txt}) {
        this.currentlineNum = lineNum
        this.playingLyric = txt
        // 当歌词播放超过5行时，要歌词滚动
        if (lineNum > 5) {
          let lyricNum = this.$refs.lyricLine[lineNum - 5]
          this.$refs.lyricList.scrollToElement(lyricNum, 1000)
        } else {
          this.$refs.lyricList.scrollToElement(0, 0, 1000)
        }
      },
      // cd缩放的倍数确定
      _getPosAndScale () {
        // mini播放器的icon宽
        const targetWidth = 40
        // icon的左边距
        const paddingLeft = 40
        // Icon的paddingbottom
        const paddingBottom = 30
        // cd的上边距
        const paddingTop = 80
        // cd的宽
        const cdWidth = window.innerWidth * 0.8
        // 初始cd的x移动距离
        const x = -(cdWidth / 2 - paddingLeft - targetWidth / 2)
        // 初始cd的y移动距离
        const y = window.innerHeight - paddingTop - cdWidth / 2 - targetWidth / 2 - paddingBottom
        //  缩小的倍数
        const scale = targetWidth / cdWidth
        return {
          x,
          y,
          scale
        }
      },
      ...mapMutations({
        setFullScreen: 'SET_FULLSCREEN',
        setPlaying: 'SET_PLAYING',
        setPlayList: 'SET_PLAY_LIST',
        setCurrentIndex: 'SET_CURRENT_INDEX',
        setMode: 'SET_MODE'
      })
    },
    computed: {
      // 动态给播放模式绑定样式
      iconMode () {
        return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
      },
      ...mapGetters([
        'currentIndex',
        'fullScreen',
        'playlist',
        'sequenceList',
        'currentSong',
        'playing',
        'mode'
      ]),
      // cdWrapper旋转
      cdCls () {
        return this.playing ? 'play' : 'play pause'
      },
      // 切换播放按钮的样式
      playIcon () {
        return this.playing ? 'icon-pause' : 'icon-play'
      },
      // 切换mini播放的按钮
      playMiniIcon () {
        return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
      },
      // 已播放的比例
      percent () {
        return this.currentTime / this.currentSong.duration
      }
    },
    watch: {
      playing (newVal) {
        setTimeout(() => {
          const audio = this.$refs.audio
          newVal ? audio.play() : audio.pause()
        }, 100)
      },
      currentSong (newSong, oldSong) {
        if (newSong.id === oldSong.id) {
          return false
        }
        // 切换歌曲时，要先清除当前歌词
        if (this.currentLyric) {
          this.currentLyric.stop()
        }
        this.currentSong.getSongLyric().then((lyric) => {
          this.currentLyric = new Lyric(lyric, this.handleLyric)
          if (this.playing) {
            this.currentLyric.play()
          }
        })
      }
    },
    components: {
      ProgressBar,
      ProgressCircle,
      Scroll,
      PlayList
    }
  }
</script>

<style scoped lang="stylus">
  @import "~common/stylus/variable.styl"
  @import "~common/stylus/mixin.styl"
  .player
    .normal-player
      position: fixed
      top: 0
      left: 0
      right: 0
      bottom: 0
      z-index: 150
      background-color: $color-background

      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)

      .top
        position: relative
        margin-bottom: 25px

        .back
          position: absolute
          top: 0
          left: 6px
          z-index: 50

          .icon-back
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
            transform: rotate(-90deg)

        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text

        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text

      .middle
        position: fixed
        top: 80px
        width: 100%
        bottom: 170px
        white-space: nowrap
        font-size: 0

        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%

          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%

            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%

              &.play
                animation: rotate 20s linear infinite

              &.pause
                animation-play-state: paused

              img
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%

          .playing-lyric-wrapper
            width: 100%
            margin: 30px 0 auto 0
            text-align: center
            overflow: hidden

            .playing-lyric
              height: 20px
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l

        .middle-r
          display: inline-block
          width: 100%
          height: 100%
          overflow: hidden

          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center

            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium

              &.current
                color: $color-text

      .bottom
        position: absolute
        bottom: 50px
        width: 100%

        .dot-wrapper
          text-align: center
          font-size: 0

          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l

            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll

        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0 auto
          padding: 10px 0

          .progress-bar-wrapper
            flex: 1

          .time
            flex: 0 0 30px
            width: 30px
            font-size: $font-size-small
            color: $color-text

            &.time-r
              text-align: right

            &.time-l
              text-align: left

        .operators
          display: flex
          align-items: center

          .icon
            flex: 1
            color: $color-theme

            i
              font-size: 30px

          .i-left
            text-align: right

          .i-center
            padding: 0 20px
            text-align: center

            i
              font-size: 40px

          .i-right
            text-align: left

          .icon-favorite
            color: $color-sub-theme

      &.normal-enter-active, &.normal-leave-active
        transition: all 1s

        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)

      &.normal-enter, &.normal-leave-to
        opacity: 0

        .top
          transform: translate3d(0, -100px, 0)

        .bottom
          transform: translate3d(0, 100px, 0)

  .mini-player
    position: fixed
    display: flex
    align-items: center
    z-index: 180
    left: 0
    bottom: 0
    width: 100%
    height: 60px
    background: $color-highlight-background

    &.mini-enter-active, &.mini-leave-active
      transition: all 0.4s

    &.mini-enter, &.mini-leave-to
      opacity: 0

    .icon
      flex: 0 0 40px
      width: 40px
      padding: 0 10px 0 20px

      img
        border-radius: 50%

        &.play
          animation: rotate 10s linear infinite

        &.pause
          animation-play-state: paused

    .text
      display: flex
      flex-direction: column
      justify-content: center
      flex: 1
      line-height: 20px
      overflow: hidden

      .name
        margin-bottom: 2px
        no-wrap()
        font-size: $font-size-medium
        color: $color-text

      .desc
        no-wrap()
        font-size: $font-size-small
        color: $color-text-d

    .control
      flex: 0 0 30px
      width: 30px
      padding: 0 10px

      .icon-mini
        font-size: 32px
        position: absolute
        left: 0
        top: 0

      .icon-play-mini, .icon-pause-mini, .icon-playlist
        font-size: 30px
        color: $color-theme-d

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>
